package net.xo68.destiny.manager.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.node.NodeRegistry;
import net.xo68.destiny.manager.entity.NodeHeartbeat;
import net.xo68.destiny.manager.mapper.NodeHeartbeatMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;



/** 
 * NodeHeartbeat Service
 * @author wuxie(16349023@qq.com)
 * @date 2020年11月06日 22:25:25
 *
 */
@Slf4j
@Service
public class NodeHeartbeatService{
    
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private NodeHeartbeatMapper nodeHeartbeatMapper;



    public NodeHeartbeat find(String nodeHost) {
        return  nodeHeartbeatMapper.find(nodeHost);
    }

    public NodeHeartbeat insert(NodeHeartbeat nodeHeartbeat) {
        nodeHeartbeatMapper.insert(nodeHeartbeat);
        return nodeHeartbeat;
    }

    public NodeHeartbeat update(NodeHeartbeat nodeHeartbeat) {
        nodeHeartbeatMapper.update(nodeHeartbeat);
        return nodeHeartbeat;
    }
    
    public int delete(String nodeHost,String nodeTypeName) {
        return nodeHeartbeatMapper.delete(nodeHost,nodeTypeName);
    }
    
    public List<NodeHeartbeat> list() {
        return nodeHeartbeatMapper.list();
    }
    public List<NodeHeartbeat> validList(long timeoutSecond) {
        return nodeHeartbeatMapper.validList(timeoutSecond);
    }

    public int removeExpired(long timeoutSecond){
        return nodeHeartbeatMapper.removeExpired(timeoutSecond);
    }
	
	public PageInfo<NodeHeartbeat> list(int pageNumber,int pageSize) {
        PageHelper.startPage(pageNumber, pageSize,true);
        List<NodeHeartbeat> docs = nodeHeartbeatMapper.list();
        PageInfo<NodeHeartbeat> pageInfo = new PageInfo<NodeHeartbeat>(docs);
        return pageInfo;
    }

    /**
     * 更新心跳
     * @param nodeRegistry
     */
    public void UpdateHeartbeat(NodeRegistry nodeRegistry){
        NodeHeartbeat nodeHeartbeat=new NodeHeartbeat();
        nodeHeartbeat.setNodeHost(nodeRegistry.getNodeHost());
        nodeHeartbeat.setWorkGroupName(nodeRegistry.getWorkGroup());
        nodeHeartbeat.setNodeTypeName(nodeRegistry.getNodeType().name());
        nodeHeartbeat.setCpuUsage(nodeRegistry.getCpuUsage());
        nodeHeartbeat.setMemoryUsage(nodeRegistry.getMemoryUsage());
        nodeHeartbeat.setLoadAverage(nodeRegistry.getLoadAverage());
        nodeHeartbeat.setLastTime(nodeRegistry.getLastTime());
        int effect=nodeHeartbeatMapper.update(nodeHeartbeat);
        if(effect<1){
            effect=nodeHeartbeatMapper.insert(nodeHeartbeat);
        }
    }
}